import {
  AfterViewInit,
  Component,
  OnDestroy,
  Input,
  Output,
  EventEmitter
} from '@angular/core'

@Component({
  selector: 'app-countdown',
  templateUrl: './countdown.component.html',
  styleUrls: ['./countdown.component.scss']
})
export class CountdownComponent implements AfterViewInit, OnDestroy {
  // 父组件传递截止日期
  @Input() enddate: number
  // 父组件传递标题
  @Input() title: string
  // 父组件类型
  @Input() type: string
  @Output() callGetList = new EventEmitter()

  time: string
  day: number
  // 小时差
  hour: number
  // 分钟差
  minute: number
  // 秒数差
  second: number
  // 时间差
  private _diff: number

  private get diff() {
    return this._diff
  }
  
  private set diff(val) {
    this._diff = Math.floor(val / 1000)
    this.day = Math.floor(this._diff / (24 * 60 * 60))
    this.hour = Math.floor((this._diff % (24 * 60 * 60)) / 3600)
    this.minute = Math.floor((this._diff % 3600) / 60)
    this.second = (this._diff % 3600) % 60
    this.timeTransform()

  }
  // 定时器
  private timer

  ngOnInit() {
    this.diff = this.enddate - Date.now()
  }

  // 每一秒更新时间差
  ngAfterViewInit() {
    this.diff = this.enddate - Date.now()
    if (this.diff <= 0) {
      clearInterval(this.timer)
      this.callGetList.emit()
    }
    else {
      this.timer = setInterval(() => {
        this.diff = this.enddate - Date.now()
        if (this.diff <= 0) {
          clearInterval(this.timer)
          this.callGetList.emit()
        }
      }, 1000)
    }
  }

  // 销毁组件时清除定时器
  ngOnDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }

  timeTransform() {
    var h = this.hour > 9 ? this.hour : "0" + this.hour;
    var m = this.minute > 9 ? this.minute : "0" + this.minute;
    var s = this.second > 9 ? this.second : "0" + this.second;
    this.time = h + ":" + m + ":" + s;
  }
}
